package com.fengye.security.jwt.process;

import com.pearadmin.common.tools.jwt.Auth0JwtUtil;
import com.pearadmin.common.tools.servlet.ServletUtil;
import com.pearadmin.common.web.domain.response.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * 登陆验证成功处理,返回jwtToken
 */
@Component("jwtAuthenticationSuccessHandler")
@Slf4j
public class JwtAuthenticationSuccessHandler extends SimpleUrlAuthenticationSuccessHandler {

	@Override
	public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
										Authentication authentication) throws IOException {

//		MyUserDetails userDetails = (MyUserDetails) authentication.getPrincipal();
		// String json = JSON.toJSONString(jwtUserDetails);
		// String username = userDetails.getUsername();

		// 签发token
//		Map<String, String> body = new HashMap<>();
//		body.put("id", userDetails.getId().toString());
//		try {
//			String token = JwtUtils.createToken(body);
//			ResponseUtil.success(response, token, HttpStatus.OK);
//		} catch (Exception e) {
//			e.printStackTrace();
//		}
		// String jwtToken = JwtUtils.createJwtToken(username, JwtConstant.DEFAULT_TOKEN_TIME_MS);
		//
		// response.setContentType(MediaType.APPLICATION_JSON_VALUE);
		// response.setCharacterEncoding("utf-8");
		// PrintWriter writer = response.getWriter();
		// writer.write(JSON.toJSONString(ResponseResult.success(jwtToken)));
		// writer.flush();

		Map<String, String> map = new HashMap<>();
		map.put("username", ((UserDetails)authentication.getPrincipal()).getUsername());
		String token = Auth0JwtUtil.create(map);
		Map<String, Object> res = new HashMap<>();
		res.put("token", token);
		Result<Map<String, Object>> result = Result.success(res);
		ServletUtil.write(result);
	}

}